/**
 * Created by ruwang on 10/19/14.
 */
var SPLATTER_COMMON_AND_CONSTANTS = require('./ConstantAndCommon.js');
var crypto = require('crypto');
var fs = require('fs');

generateGlobalKeyAndIV = function() {
    /*var ciphers = crypto.getCiphers();
    console.log(ciphers);*/
    global.config.AES_KEY = crypto.randomBytes(SPLATTER_COMMON_AND_CONSTANTS.Constants.NUM.AES_KEY_SIZE).toString('base64');
    global.config.AES_IV = crypto.randomBytes(SPLATTER_COMMON_AND_CONSTANTS.Constants.NUM.AES_IV_SIZE).toString('base64');
}

getOptionsSet = function(key,iv) {
    return {
        algo : SPLATTER_COMMON_AND_CONSTANTS.Constants.TEXT.AES_SUIT,
        key :  new Buffer(key, 'base64'),
        iv:  new Buffer(iv, 'base64')
    }
}

encrypt = function(inputPath, outputPath, options) {

    console.log(options);

    var keyBuf = new Buffer(options.key);
    var ivBuf = new Buffer(options.iv);
    var inputStream = fs.createReadStream(inputPath);
    var outputStream = fs.createWriteStream(outputPath);

    var cipher = crypto.createCipheriv(options.algo, options.key, options.iv);

    inputStream.on('data', function(data) {
        var buf = new Buffer(cipher.update(data,'binary','binary'), 'binary');
        outputStream.write(buf);
    });

    inputStream.on('end', function() {
        var buf = new Buffer(cipher.final('binary'), 'binary');
        outputStream.write(buf);
        outputStream.end();
    });
};


decrypt = function(inputPath, outputPath, options) {
    console.log(options);

    var keyBuf = new Buffer(options.key);
    var ivBuf = new Buffer(options.iv);
    var inputStream = fs.createReadStream(inputPath);
    var outputStream = fs.createWriteStream(outputPath);
    var cipher = crypto.createDecipheriv(options.algo, options.key, options.iv);

    inputStream.on('data', function(data) {
        var buf = new Buffer(cipher.update(data,'binary', 'binary'), 'binary');
        outputStream.write(buf);

    });

    inputStream.on('end', function() {
        var buf = new Buffer(cipher.final('binary'), 'binary');
        outputStream.write(buf);
        outputStream.end();
    });
};

module.exports.GetGlobalOptionSet = getOptionsSet;
module.exports.GlobalKeyAndIV = generateGlobalKeyAndIV;
module.exports.DoEncryptFile = encrypt;
module.exports.DoDecryptFile = decrypt;